package com.lilicould.controller;

import com.google.gson.Gson;
import com.lilicould.entity.Schedules;
import com.lilicould.service.ScheduleService;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/schedule/*")
public class ScheduleController extends BaseServlet{
    // 获取指定教师下的所有课程安排
    public void listByTeacherUserNo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        // 获取教师编号
        String userNo = req.getParameter("userNo");
        String result = new ScheduleService().getSchedulesByTeacherUserNo(userNo);

        if (result != null) {
            // 若返回数据非空，说明成功获取到数据，则返回数据给前端
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(result);
        }else {
            // 若返回结果为空，说明获取数据失败，则返回错误信息给前端
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    public void listAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json");

        // 获取所有课程安排
        String result = new ScheduleService().getAllSchedules();

        if (result != null) {
            // 若返回数据非空，说明成功获取到数据，则返回数据给前端
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(result);
        }else {
            // 若返回结果为空，说明获取数据失败，则返回错误信息给前端
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    public void add(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json");
        // 获取前端传递的参数并封装到Schedules对象中
        Schedules schedule = new Gson().fromJson(req.getReader(), Schedules.class);

        // 调用Service层方法添加课程安排
        String result = new ScheduleService().addSchedule(schedule);
        if (result != null) {
            // 若存在错误信息，则返回400状态码和错误信息
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().print(result);
        } else {
            // 添加成功，返回200状态码
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }

    public void delete(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json");

        // 获取前端传递的参数
        int scheduleId =Integer.parseInt(req.getParameter("scheduleId"));
        // 调用Service层方法删除课程安排
        String result = new ScheduleService().deleteSchedule(scheduleId);
        if (result != null) {
            // 若存在错误信息，则返回400状态码和错误信息
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().print(result);
        } else {
            // 删除成功，返回200状态码
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }
}
